﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using YunSpace.Core;
using YunSpace.Data;
using YunSpace.Domain.Entity.MiniSite;
using YunSpace.Domain.IRepository.MiniSite;
using YunSpace.Domain.ViewModel.MiniSite;
using YunSpace.Repository.MiniSite;

namespace YunSpace.Application.MiniSite
{
    public class StrategyApp
    {
        private IStrategyRepository service = new StrategyRepository();
        public List<StrategyActionModel> GetStrategyList(string lastId, int count,string customerId) {
            using (var db = new RepositoryBase()) {
                var strSql = @"select a.F_Id,a.F_title,b.path photoUrl,a.F_outline,''  F_content,a.F_activityId,
                                a.F_DeleteMark,a.F_CreatorTime,a.F_CreatorUserId,a.F_LastModifyTime,a.F_LastModifyUserId,a.F_DeleteTime,a.F_DeleteUserId,
                                case when fa.f_favoriteid is null then 0 else 1 end F_isfavorite from MiniSite_Strategy a 
                                left join SL_Photos b on a.F_Id=b.photoable_id and b.photoable_type='Strategy' 
                                left join (select distinct f_favoriteid from MiniSite_Favorite where F_Type=3 AND F_Status=1  {1}) fa on a.F_Id=fa.f_favoriteid
                                left join MiniSite_SiteActivity c on a.F_activityId=c.F_Id
                                where a.F_DeleteUserId is null 
                                {0} order by a.F_CreatorTime desc limit 0,@count";
                strSql = string.Format(strSql, lastId.IsNullOrEmpty()?"": " AND a.F_CreatorTime<(select F_CreatorTime from MiniSite_Strategy where F_Id=@fId)", customerId.IsNullOrEmpty()? " and F_CustomerId=''" : "and F_CustomerId=@customerId");
                DbParameter[] parameter =
                {
                   new MySqlParameter("@fId", lastId),
                   new MySqlParameter("@count", count),
                   new MySqlParameter("@customerId",customerId)
                };
                return db.FindList<StrategyActionModel>(strSql,parameter);
            }
        }

        public StrategyActionModel GetStrategyDetail(string id, string customerId) {
            using (var db = new RepositoryBase()) {
                var strSql = @"select a.F_Id,a.F_title,b.path photoUrl,a.F_outline,a.F_content,a.F_activityId,
                                a.F_DeleteMark,a.F_CreatorTime,a.F_CreatorUserId,a.F_LastModifyTime,a.F_LastModifyUserId,a.F_DeleteTime,a.F_DeleteUserId,
                                case when fa.f_favoriteid is null then 0 else 1 end F_isfavorite from MiniSite_Strategy a 
                                left join SL_Photos b on a.F_Id=b.photoable_id and b.photoable_type='Strategy' 
                                left join (select distinct f_favoriteid from MiniSite_Favorite where  F_Status=1  AND F_Type=3  {1}) fa on a.F_Id=fa.f_favoriteid
                                left join MiniSite_SiteActivity c on a.F_activityId=c.F_Id 
                                where 1=1 {0}";
                strSql = string.Format(strSql,id.IsNullOrEmpty()?"":"and a.f_id=@id", customerId.IsNullOrEmpty()? " and F_CustomerId=''" : "and F_CustomerId=@customerId");
                DbParameter[] parameter =
                {
                   new MySqlParameter("@id", id),
                   new MySqlParameter("@customerId",customerId)
                };
                return db.FindList<StrategyActionModel>(strSql, parameter).FirstOrDefault();
            }
        }

        public bool GetStrategyCollect(string id,string customerId,string url,ref string msg) {
            try
            {
                using (var db = new RepositoryBase().BeginTrans())
                {
                    var strSql = @"select * from MiniSite_Favorite a where a.F_FavoriteId=@id and a.F_CustomerId=@customerId";
                    DbParameter[] parameter =
                    {
                       new MySqlParameter("@id", id),
                       new MySqlParameter("@customerId",customerId)
                    };
                    IFavoriteRepository faservice = new FavoriteRepository();
                    FavoriteEntity entity = db.FindList<FavoriteEntity>(strSql, parameter).FirstOrDefault();
                    if (entity != null)
                    {
                        entity.F_Status = !entity.F_Status;
                        entity.F_URL = url;
                        faservice.Update(entity);
                        if (entity.F_Status == true)
                        {
                            msg = "攻略成功收藏！";
                        }
                        else {
                            msg = "攻略取消收藏！";
                        }
                    }
                    else
                    {
                        entity = new FavoriteEntity();
                        entity.Create();
                        entity.F_CustomerId = customerId;
                        entity.F_FavoriteId = id;
                        entity.F_URL = url;
                        entity.F_Type = "3";
                        entity.F_Status = true;
                        faservice.Insert(entity);
                        msg = "活动成功收藏！";
                    }

                    db.Commit();
                }
                return true;
            }
            catch (Exception ex) {
                return false;
            }
        }

        public List<StrategyEntity> GetList(Pagination pagination, string queryJson)
        {
            var expression = ExtLinq.True<StrategyEntity>();
            var queryParam = queryJson.ToJObject();
            if (!queryParam["keyword"].IsEmpty())
            {
                string keyword = queryParam["keyword"].ToString();
                expression = expression.And(t => t.F_title.Contains(keyword));
            }
            // if (!queryParam["timeType"].IsEmpty())
            // {
            //     string timeType = queryParam["timeType"].ToString();
            //     DateTime startTime = DateTime.Now.ToString("yyyy-MM-dd").ToDate();
            //     DateTime endTime = DateTime.Now.ToString("yyyy-MM-dd").ToDate().AddDays(1);
            //     switch (timeType)
            //     {
            //         case "1":
            //             break;
            //         case "2":
            //             startTime = DateTime.Now.AddDays(-7);
            //             break;
            //         case "3":
            //             startTime = DateTime.Now.AddMonths(-1);
            //             break;
            //         case "4":
            //             startTime = DateTime.Now.AddMonths(-3);
            //             break;
            //         default:
            //             break;
            //     }
            //     expression = expression.And(t => t.F_Date >= startTime && t.F_Date <= endTime);
            // }
            return service.FindList(expression, pagination);
        }

        public StrategyEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public void DeleteForm(string keyValue)
        {
            service.Delete(t => t.F_Id == keyValue);
        }
        public void SubmitForm(StrategyEntity strategyEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                strategyEntity.Modify(keyValue);
                service.Update(strategyEntity);
            }
            else
            {
                strategyEntity.Create();
                // strategyEntity.F_Category = 2;
                service.Insert(strategyEntity);
            }
        }
    }
}
